"""Code for handling passwords."""

import base64
import crypt
import hashlib
import os
import random
import string

from django.conf import settings

def hash_pw(password):
    """Hash a password.

    :Parameters:
        - `password`: The password to hash.

    :Return:
        Returns the hashed value with the scheme prefix.
    """
    return globals()['_hash_'+settings.HCP_PASSWORD_SCHEME.lower()](password)

def _hash_ssha(password):
    salt = os.urandom(4)
    h = hashlib.sha1(password)
    h.update(salt)
    return '{SSHA}' + base64.b64encode(h.digest() + salt)

def _hash_crypt(password):
    salt_chars = './' + string.ascii_letters + string.digits
    salt = random.choice(salt_chars) + random.choice(salt_chars)
    h = crypt.crypt(password, salt)
    return '{CRYPT}' + h

def _hash_md5(password):
    h = hashlib.md5(password)
    return '{MD5}' + base64.b64encode(h.digest())

def _hash_smd5(password):
    salt = os.urandom(4)
    h = hashlib.md5(password)
    h.update(salt)
    return '{SMD5}' + base64.b64encode(h.digest() + salt)

def _hash_sha(password):
    h = hashlib.sha1(password)
    return '{SHA}' + base64.b64encode(h.digest())
